package com.iwayin.web.common;

import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.dispatcher.ServletRedirectResult;

import com.opensymphony.xwork2.ActionInvocation;

/**
 * 扩展struts2返回类型，直接返回String
 * 
 * @author xiaobo.feng<xiaobo.feng@foxmail.com>
 * 
 *         Nov 28, 2011
 */
public class StringResult extends ServletRedirectResult {

	/**
	 * 
	 */
	private static final long serialVersionUID = 8073964440057652497L;

	private static final Log LOG = LogFactory.getLog(StringResult.class);

	public StringResult() {
		super();
	}

	public StringResult(String location) {
		super(location);
	}

	@Override
	public void doExecute(String finalLocation, ActionInvocation invocation)
			throws Exception {
		HttpServletResponse response = (HttpServletResponse) invocation
				.getInvocationContext().get(HTTP_RESPONSE);

		HttpServletRequest request = (HttpServletRequest) invocation
				.getInvocationContext().get(HTTP_REQUEST);

		response.setContentType("text/plain; charset=UTF-8");

		response.setHeader("Content-Disposition", "inline");

		PrintWriter writer = null;

		try {

			writer = response.getWriter();

			writer.write(request.getAttribute(finalLocation).toString());

		} catch (NullPointerException e) {
			if (finalLocation.equals("")) {
				LOG.warn("未指定value", e);
			} else {
				LOG.error("空", e);
			}
		} finally {
			if (writer != null) {
				writer.flush();
				writer.close();
			}
		}
	}
}
